<?php

class model_creator {
 	
	private $ci;
	
 	public function __construct()
 	{
 		log_message('debug', 'Model creator library initialized.');
		
		$this->ci =& get_instance();
 	}
 	
	
	
	public function make_model($sTableName, $sClassName = null, $sFileName)
	{
		if ($sClassName === null)
		{
			$sClassName = $sTableName;	
		}
		
		$aFields = $this->ci->db->field_data($sTableName);

		$sFields = '';

		$sPrimaryKey = '';

		foreach ($aFields as $oField)
		{
			$sFields .= 'public $'.$oField->name.' = false;'.PHP_EOL;
			
			if ($oField->primary_key === 1)
			{
				$sPrimaryKey = $oField->name;
			}
		} 
	
	
		$this->ci->load->helper('file');
		
		$sFile = read_file('system/application/model_structure/model.php');
			
		$aPatterns = array('/_TABLE_NAME_/', '/_FIELD_NAME_DECLARATIONS_/', '/_PRIMARY_KEY_/', '/_CLASS_NAME_/');
		$aReplacements = array($sTableName, $sFields, $sPrimaryKey, $sClassName);
		
		$sFile = preg_replace($aPatterns, $aReplacements, $sFile);
		
		$sFilePath = 'system/application/models/db/'.$sFileName.'.php';
		
		if (file_exists($sFilePath) !== true)
		{
			write_file($sFilePath, $sFile);
		
			echo $sFilePath.'<hr />';
		}
	}

}

?>